﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Text.RegularExpressions;
namespace THS.HtmlHelpers
{
	public static class RoutingHelper
	{
        //public RequestContext RequestContext { get; set; }

        ///// <summary>
        ///// Initializes a new instance of the <see cref="RoutingHelper"/> class.
        ///// </summary>
        //public RoutingHelper()
        //{
        //}
        public class Friendly
        {
            public string Url { get; set; }
            public string ActionName { get; set; }
            public string ControllerName { get; set; }
            public RouteValueDictionary RouteValues { get; set; }
            public MvcHtmlString HtmlSafeUrl
            {
                get
                {
                    return MvcHtmlString.Create(Url);
                }
            }
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="RoutingHelper"/> class.
		/// </summary>
		/// <param name="requestContext">The request context.</param>
        //public RoutingHelper( RequestContext requestContext )
        //{
        //    this.RequestContext = requestContext;
        //}

		/// <summary>
		/// Gets a parameterized virtual path.
		/// </summary>
		/// <param name="values">The values.</param>
		/// <returns></returns>
        //public static string VirtualPath( object values )
        //{
        //    return VirtualPath( null, values );
        //}

		/// <summary>
		/// Gets a parameterized virtual path.
		/// </summary>
		/// <param name="routeName">The route name.</param>
		/// <param name="values">The values.</param>
		/// <returns></returns>
        //public static string VirtualPath( string routeName, object values )
        //{
        //    return ( RequestContext != null )
        //        ? RouteTable.Routes.GetVirtualPath( RequestContext, routeName, new RouteValueDictionary( values ) ).VirtualPath
        //        : null;
        //}

		/// <summary>
		/// Returns an HTML anchor.
		/// </summary>
		/// <param name="url">The URL.</param>
		/// <returns></returns>
        //public string ActionLink( string url )
        //{
        //    return ActionLink( url, url );
        //}

		/// <summary>
		/// Returns an HTML anchor.
		/// </summary>
		/// <param name="url">The URL.</param>
		/// <param name="text">The text.</param>
		/// <returns></returns>
		public static string ActionLink( string url, string text )
		{
			return string.Format( "<a href=\"{0}\">{1}</a>", url, text );
		}

		/// <summary>
		/// Gets a route value.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <returns></returns>
        //public object Value( string key )
        //{
        //    return ( RequestContext != null ) ? RequestContext.RouteData.Values[ key ] : null;
        //}

		/// <summary>
		/// Gets the base URL.
		/// </summary>
		/// <value>The base URL.</value>
        //public string BaseUrl
        //{
        //    get { return RequestContext.HttpContext.Request.Url.GetLeftPart( UriPartial.Authority ) + VirtualPathUtility.ToAbsolute( "~/" ); }
        //}

		/// <summary>
		/// Gets SiteMap path for the current request.
		/// </summary>
		/// <returns></returns>
        //public string SiteMapPath()
        //{
        //    var pages = SiteMap.CurrentNode.For( n => n != null, n => n.ParentNode ).Reverse().Select( n => SiteMapLink( n ) );

        //    return string.Join( " > ", pages.ToArray() );
        //}

		/// <summary>
		/// Gets a SiteMap link.
		/// </summary>
		/// <param name="node">The node.</param>
		/// <returns></returns>
        //private string SiteMapLink( SiteMapNode node )
        //{
        //    var span = string.Format( "<span class=\"siteMapLink\">{0}</span>", node.Title );

        //    return ( node != SiteMap.CurrentNode )
        //        ? string.Format( "<a href=\"{0}\">{1}</a>", node.Url, span )
        //        : span;
        //}

        public static MvcHtmlString ToFriendlyURL(this HtmlHelper helper,String actionName,String controllerName,RouteValueDictionary routeValues, String originalText, IDictionary<string, object> htmlAttributes)
        {
           
            string cleanUrl = Regex.Replace(originalText, @"[^a-z0-9\s-]", "-"); // invalid chars
            cleanUrl = Regex.Replace(originalText, @"\s+", "-").Trim(); // convert multiple spaces into one
            var friendly = helper.FriendLyUrl(actionName,controllerName,routeValues,originalText);
            //var link = helper.RouteLink(language.IsSelected ? selectedText : unselectedText,
            //    "THSLocalization", friendly.RouteValues, htmlAttributes);
            var link = helper.RouteLink(originalText, friendly.RouteValues, htmlAttributes);
            return MvcHtmlString.Create(link.ToString());
            
        }
        public static Friendly FriendLyUrl(this HtmlHelper helper, String actionName, String controllerName, RouteValueDictionary routeValues, string originalText)
        {
        
           // var routeValues = new RouteValueDictionary(helper.ViewContext.RouteData.Values);
            // copy the query strings into the route values to generate the link
            var queryString = helper.ViewContext.HttpContext.Request.QueryString;
            foreach (string key in queryString)
            {
                if (queryString[key] != null && !string.IsNullOrWhiteSpace(key))
                {
                    if (routeValues.ContainsKey(key))
                    {
                        routeValues[key] = queryString[key];
                    }
                    else
                    {
                        routeValues.Add(key, queryString[key]);
                    }
                }
            }
            //var actionName = routeValues["action"].ToString();
            //var controllerName = routeValues["controller"].ToString();
            // set the language into route values
            //routeValues[languageRouteName] = cultureName;
            // generate the language specify url
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection);
            var url = urlHelper.RouteUrl("THSLocalization", routeValues);
            // check whether the current thread ui culture is this language
            //var current_lang_name = Thread.CurrentThread.CurrentUICulture.Name.ToLower();
            //var isSelected = strictSelected ? current_lang_name == cultureName : current_lang_name.StartsWith(cultureName);
            return new Friendly()
            {
                Url = url.Replace("?", @"/").Replace("=", @"/"),
                //Url = url,
                ActionName = actionName,
                ControllerName = controllerName,
                RouteValues = routeValues
            };
        }
	}
}